package config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.same.SaSameUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import common.dtos.ResponseResult;
import common.enums.HttpCodeEnum;
import interceptor.MicroServiceInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Sa-Token 权限认证 配置类
 * description: Sa-Token 配置类
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Autowired
    private ObjectMapper objectMapper;

    String[] excludePatterns = new String[]{
            "/doc.html",
            "/doc.html*",
            "/webjars/**",
            "/img.icons/**",
            "/swagger-resources/**",
            "/**/v2/api-docs",
            "/favicon.ico",
    };

    // 注册 Sa-Token 全局过滤器
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude(excludePatterns)
                .setAuth(obj -> {
                    // 校验 Same-Token 身份凭证     —— 以下两句代码可简化为：SaSameUtil.checkCurrentRequestToken();
                    String token = SaHolder.getRequest().getHeader(SaSameUtil.SAME_TOKEN);
                    SaSameUtil.checkToken(token);
                })
                .setError(e -> {
                    try {
                        return objectMapper.writeValueAsString(ResponseResult.get(HttpCodeEnum.CROSS_GATEWAY_REQUEST));
                    } catch (JsonProcessingException ex) {
                        throw new RuntimeException(ex);
                    }
                });
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        // 实现@SaInterior注解
        registry.addInterceptor(new MicroServiceInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(excludePatterns);
    }
}
